package com.example.demo.service.impl;

import com.example.demo.entity.Deparment;
import com.example.demo.entity.Role;
import com.example.demo.entity.User;
import com.example.demo.entity.repository.DeparmentRepository;
import com.example.demo.entity.repository.RoleRespository;
import com.example.demo.entity.repository.UserRepository;
import com.example.demo.service.AService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

@Service
public class AServiceImpl implements AService {
    private static Logger logger = LoggerFactory.getLogger(AServiceImpl.class);
    @Autowired
    UserRepository userRepository;
    @Autowired
    DeparmentRepository deparmentRepository;

    @Autowired
    RoleRespository roleRespository;
    @Override
    public void findPage() {

        initDate();

        Pageable pageable= new PageRequest(0,10,new Sort(Sort.Direction.ASC,"id"));

        Page<User> page = userRepository.findAll(pageable);
        Assert.isNull(page);

        for (User user:page.getContent()){
            logger.info("===user====user name:{},deparment name{},role name{}",user.getName(),user.getDeparment(),user.getRoles());
        }
    }

    public void initDate(){
        userRepository.deleteAll();
        deparmentRepository.deleteAll();
        roleRespository.deleteAll();

        Deparment deparment= new Deparment();

        deparment.setName("开发部");

        deparmentRepository.save(deparment);

        Assert.isNull(deparment.getId());

        Role role= new Role();
        role.setName("admin");

        roleRespository.save(role);
        Assert.isNull(role.getId());

        User user = new User();
        user.setName("user");
        user.setCreateDate(new Date());
        user.setDeparment(deparment);

        List<Role> roles= roleRespository.findAll();
        Assert.isNull(roles);
        user.setRoles(roles);

        userRepository.save(user);

        Assert.isNull(user.getId());

    }
}
